<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/21 18:18
 * Remark:
 */

namespace App\Service\Department;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Models\Company\CompanyModel;
use App\Models\Department\DepartmentModel;
use App\ServiceChecker\Department\DeptLegitimacy;
use Illuminate\Http\Exceptions\HttpResponseException;

class DepartmentService
{
    private DepartmentModel $_departmentModel;
    private DeptLegitimacy $deptLegitimacy;

    public function __construct()
    {
        $this->_departmentModel = new DepartmentModel();
        $this->deptLegitimacy = new DeptLegitimacy();
    }

    private function _createCompanyModel(): CompanyModel
    {
        return new CompanyModel();
    }

    /**
     * 获取部门等级
     * @param $departmentParentId
     * @return string
     */
    private function _getDepartmentLevel($departmentParentId): string
    {
        $departmentParentInfo = $this->_departmentModel->getDepartmentInfoByDepartmentIdModel($departmentParentId);
        // 计算部门等级
        // 当部门等级为2级时 设置等级为 父部门.1 当部门为2级以上时 设置等级为 父部门.1.1
        if($departmentParentInfo['department_level'] == 1){
            $departmentLevel = $departmentParentInfo['department_id'].".";
        }else{
            $departmentLevel = $departmentParentInfo['department_level'].$departmentParentInfo['department_id'].".";
        }
        return $departmentLevel;
    }


    private function checkerAddDepartmentService($args){
        // 校验公司是否存在
        $this->deptLegitimacy->verifyCompanyIsExists($args['company_id']);
        // 新增的时候校验名称是否重复
        $this->deptLegitimacy->verifyCompanyDepartmentNameIsExists($args['department_name'],$args['company_id']);
        if($args['department_parent_id']){
            $this->deptLegitimacy->verifyCompanyDepartmentIsExists($args['department_parent_id'],$args['company_id']);
        }
    }

    /**
     * 新增部门Service
     * @param $departmentData
     * @return bool
     */
    public function addDepartmentService($departmentData): bool
    {
        $this->checkerAddDepartmentService([
            'company_id' => $departmentData['company_id'],
            'department_name' => $departmentData['department_name'],
            'department_parent_id' => $departmentData['department_parent_id']
        ]);

        // 计算部门等级
        if(!isset($departmentData['department_parent_id']) || $departmentData['department_parent_id'] ==0){
            $departmentData['department_parent_id'] = 0;
            $departmentData['department_level'] = 1;
        }else{
            $departmentData['department_level'] = $this->_getDepartmentLevel($departmentData['department_parent_id']);
        }

        $departmentData = [
            $this->_departmentModel->company_id = $departmentData['company_id'],
            $this->_departmentModel->department_name = $departmentData['department_name'],
            $this->_departmentModel->department_parent_id = $departmentData['department_parent_id'],
            $this->_departmentModel->department_level = $departmentData['department_level'],
        ];

        $departmentRes = $this->_departmentModel->addDepartmentModel($departmentData);
        if(!$departmentRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "新增部门失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }

    private function checkerEditDepartmentService($args){
        // 修改的时候校验部门是否存在
        $this->deptLegitimacy->verifyDepartmentIsExists($args['department_id']);

        if($args['department_name']){
            $this->deptLegitimacy->verifyDeptNameIsExistsByEdit($args['department_id'],$args['department_name']);
        }
        if($args['department_parent_id']){
            $this->deptLegitimacy->verifyDepartmentParentIsLegal($args['department_id'],$args['department_parent_id']);
        }
    }

    /**
     * 编辑部门
     * @param $departmentData
     * @return bool
     */
    public function editDepartmentService($departmentData) :bool{
        if(isset($departmentData["department_name"]) && empty($departmentData["department_name"])){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "部门名称不能为空",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }
        $this->checkerEditDepartmentService([
            'department_id' => $departmentData['department_id'],
            'department_name' => $departmentData['department_name'] ?? false,
            'department_parent_id' => $departmentData['department_parent_id'] ?? false
        ]);

        unset($departmentData['status']);
        unset($departmentData['company_id']);
        $updateData = $departmentData;
        // 计算部门等级
        if(isset($updateData['department_parent_id'])){
            $updateData['department_level'] = $this->_getDepartmentLevel($updateData['department_parent_id']);
        }
        $departmentRes = $this->_departmentModel->editDepartmentEdit($updateData);
        if(!$departmentRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "编辑部门失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }


    private function checkerPatchEditDepartmentService($args){
        $this->deptLegitimacy->verifyDepartmentIsExists($args['department_id']);
        $this->deptLegitimacy->verifyDepartmentHasChildIsExists($args['department_id']);
    }

    /**
     * 删除部门
     * @param $departmentId
     * @return bool
     */
    public function patchEditDepartmentService($departmentId): bool
    {
        $this->checkerPatchEditDepartmentService([
            'department_id' => $departmentId
        ]);
        $departmentRes = $this->_departmentModel->editDepartmentEdit([
            'department_id' => $departmentId,
            'status' => BaseConsts::STATUS_DELETE
        ]);
        if(!$departmentRes){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "删除部门失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }
        return true;
    }

    /**
     * 通过公司ID获取部门下拉
     * @param $companyId
     * @return mixed
     */
    public function getDeptSelectByCompanyIdService($companyId): mixed
    {
        $isExist = $this->_createCompanyModel()->isExistByCondition([
            'company_id' => $companyId,
        ]);

        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "当前公司不存在或已删除",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }

        return $this->_departmentModel->getDepartmentMenuByCompanyId($companyId,[
            'department_id',
            'department_id as key',
            'department_name',
            'department_parent_id'
        ]);

    }

    /**
     * 获取部门详情
     * @param $departmentId
     * @return mixed
     */
    public function getDepartmentInfoService($departmentId): mixed
    {
        $isExist = $this->_departmentModel->isExistByCondition([
            'department_id' => $departmentId,
        ]);

        if(!$isExist){
            throw new HttpResponseException( ResponseFunc::returnJson(
                'error',
                '',
                "当前部门不存在或已存在",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                
            ));
        }

        return $this->_departmentModel->getDepartmentInfoByDepartmentIdModel($departmentId,[
            'department_id',
            'department_id as department_code',
            'department_name',
            'department_parent_id',
            'department_parent_id as department_parent_name',
            "created_at"
        ]);
    }

    public function getDeptCompanyIdByDeptId($deptId)
    {
        return $this->_departmentModel->getDeptCompanyIdByDeptId($deptId)['company_id'] ?? 0;
    }
}